package com.ztstkj.lzservices.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Environment
import com.blankj.utilcode.util.AppUtils
import com.sscl.baselibrary.utils.DebugUtil
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.InputStreamReader

@SuppressLint("StaticFieldLeak")
object LogcatUtil {
    private var command: String = ""
    private lateinit var mReader: BufferedReader
    private lateinit var output: FileOutputStream
    private var sb: StringBuilder = StringBuilder()
    private lateinit var exec: Process
    private var pId: Int?=null
    private var running: Boolean=true
    private lateinit var dir: String
    private var thread: Thread?=null
    fun close(context:Context){
        try {
            SpeakUtil.speech(context,"日志输出线程结束")
            running=false
            thread?.join()
            DebugUtil.debugOut("线程结束，不再生成日志到文件")
        }catch (e: Exception){

        }

    }
    fun start(context:Context) {
        try {
            dir = if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Environment.getExternalStorageDirectory().absolutePath + File.separator + AppUtils.getAppPackageName() + ".lz_log" // 优先保存到SD卡中
            } else {
                context.filesDir.absolutePath + File.separator+AppUtils.getAppPackageName()+ ".lz_log" // 如果SD卡不存在，就保存到本应用的目录下
            }
            var file = File(dir)
            if (!file.exists()) {
                file.mkdirs()
            }
            output = FileOutputStream(File(dir, "${DateTimeUtil.getNowDate()}.log"))
            pId = android.os.Process.myPid()
            command = "logcat  *:e *:d | grep \"($pId)\""

            exec = Runtime.getRuntime().exec(command)
            mReader = BufferedReader(InputStreamReader(exec.inputStream), 1024)
            thread= Thread {
                var line: String?=null
                try {
                    SpeakUtil.speech(context,"日志输出线程开始")
                    DebugUtil.debugOut("线程开始，生成日志到文件,$command")
                    while (running && run { line = mReader.readLine();line != null }) {
                        sb.append(line)
                        if (!running) {
                            DebugUtil.debugOut("线程:break")
                            break
                        }
                        if (line?.length == 0) {
                            continue
                        }
                        if (line != null) {
                            if (line.contains(pId.toString())) {
                                output.write("$line\n".toByteArray())
                            }
                        }
                        Thread.sleep(100)
                    }
                } catch(e: Exception) {
                    e.printStackTrace()
                }finally {
                    exec.destroy()
                    mReader.close()
                    output.close()
                }
            }
            thread?.start()
        }catch (e: Exception){

        }

    }
}